package word_to_pdf;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

import java.io.*;

/**
 * 参考：https:blog.csdn.net/ka3p06/article/details/125476270 通过documents4j实现
 */
public class TestMain02 {


    public static void main(String[] args) throws Exception {
        TestMain02 testMain = new TestMain02();
        testMain.word2pdf();
    }

    public void word2pdf() throws IOException {
        InputStream docxInputStream = null;
        OutputStream pdfOutputStream = null;
        ByteArrayOutputStream os = null;
        ByteArrayInputStream is = null;
        try {
            // 原word地址
            docxInputStream = new FileInputStream("C:\\Users\\HUAWEI\\Desktop\\fsdownload\\检查记录20230821174227.doc");
            // 转换后pdf生成地址
            pdfOutputStream = new FileOutputStream("C:\\Users\\HUAWEI\\Desktop\\fsdownload\\检查记录20230821174227.pdf");
            os = new ByteArrayOutputStream();

            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(os)
                    .as(DocumentType.PDF).execute();

            is = new ByteArrayInputStream(os.toByteArray());
            byte buff[] = new byte[1024];
            int length = 0;
            while ((length = is.read(buff)) > 0) {
                pdfOutputStream.write(buff, 0, length);
            }
            // 关闭
            converter.shutDown();
            // 关闭
            pdfOutputStream.close();
            // 关闭
            docxInputStream.close();
            os.close();
            is.close();
        } catch (Exception e) {
            System.out.println("[documents4J] word转pdf失败:" + e.toString());
        } finally {
            if (pdfOutputStream != null) {
                pdfOutputStream.close();
            }
            if (docxInputStream != null) {
                docxInputStream.close();
            }
        }
    }
}
